import axios from "./axiosConfig";
import {apiConfig} from './apiConfig';
// 接口配置

// 格式化参数
/*
	当接口为get的时候，参数要拼接到url后面，
*/
let formatParamsFn = (params) => {
  let str = [];
  for (let key in params) {
    str.push(`${key}=${params[key]}`);
  }
  return str.join("&");
}
// 获取地址，打包时，根据不同的环境获取对应的地址，比如：测试环境，生成环境
let getUrlFn = (params = {}, item = {}) => {
  return process.env.API_URL + (item.method === 'get' ? `${item.url}?${formatParamsFn(params)}` : item.url);
}
function createExcel(byteData, name,type) {
  let blob = new Blob([byteData], {
    type: type,
  });
  let fileName = name ;
  // 允许用户在客户端上保存文件
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName);
  } else {
    let link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    //释放内存
    window.URL.revokeObjectURL(link.href);
  }

}

// 工厂函数，把apiConfig下的各个模块的api配置，生成方法，等待调用
let toApiFn = (configData = null) => {
  // 接口对象
  let api = {};
  if (configData) {
    for (let modeName in configData) {
      api[modeName] = {};
      let modeApiConfig = configData[modeName] || [];
      modeApiConfig.forEach(modeItem => {
        if (modeItem && modeItem.name) {
          api[modeName][modeItem.name] = (params = {}, option = {}) => {
            let baseConfig={
              method: option.method || modeItem.method || 'post',
              url: option.url || getUrlFn(params, modeItem),
              data: params,
              headers: Object.assign({}, modeItem.headers, option.headers),
            }
            if(option.down){
              baseConfig["responseType"]="arraybuffer";
              return axios(baseConfig).then((res = {}) => {createExcel(res.data,option.down.fileName,option.down.type)});
            }else {
              return axios(baseConfig).then((res = {}) => {return res.data.entity});
            }
          }
        }
      });
    }
  }
  return api;
}
export default toApiFn(apiConfig);
